package cn.iocoder.yudao.module.orderview.mq.consumer;

import cn.iocoder.yudao.framework.redissonlock.core.annotation.RedissonLock;
import cn.iocoder.yudao.module.orderview.dal.redis.Lock4jRedisKeyConstants;
import cn.iocoder.yudao.module.orderview.dal.redis.orderview.OrderViewRedisDAO;
import cn.iocoder.yudao.module.orderview.dal.redis.orderview.snapshot.OrderViewAggregationSnapshot;
import cn.iocoder.yudao.module.product.mq.message.ProductInfoSendMessage;
import com.baomidou.lock.annotation.Lock4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import cn.iocoder.yudao.module.promotion.mq.message.PromotionInfoSendMessage;

import static cn.iocoder.yudao.module.orderview.dal.redis.RedisKeyConstants.ORDER_VIEW_TASK_PREFIX;

/**
 * 针对
 * {@link PromotionInfoSendMessage} 的消费者
 *
 * @author 徐煜东
 */
@RocketMQMessageListener( // 重点：添加 @RocketMQMessageListener 注解，声明消费的 topic
        topic = PromotionInfoSendMessage.TOPIC,
        consumerGroup = PromotionInfoSendMessage.TOPIC + "_CONSUMER"
)
@Component
@Slf4j
public class PromotionOrderViewRespConsumer implements RocketMQListener<PromotionInfoSendMessage> {

    @Resource
    OrderViewRedisDAO orderViewRedisDAO;
    @Resource
    private RedisTemplate redisTemplate;

    @RedissonLock(key = "'order_view_resp_mq_consumer:' + #message.requestId", expire = 10)
    @Override
    public void onMessage(PromotionInfoSendMessage message) {
        String requestId = message.getRequestId();
        //log.info("[onMessage][收到消息({})]", message);
        OrderViewAggregationSnapshot orderView = orderViewRedisDAO.get(requestId);
        if (orderView == null) {
            orderView = new OrderViewAggregationSnapshot(requestId);
        }
        orderView.setPromotionInfo(message);
        log.info("[onMessage][视图信息消息({})]", orderView);
        orderViewRedisDAO.set(orderView);
        if (orderView.isComplete()) {
            String rediskey = formatKey(requestId);
            redisTemplate.opsForValue().set(rediskey, "completed", 5, TimeUnit.MINUTES);
            //存储热点数据
            orderViewRedisDAO.set0(orderView);
            log.info("[onMessage][信息组装完毕({})]", orderView);
        }
    }

    private static String formatKey(String requestId) {
        return String.format(ORDER_VIEW_TASK_PREFIX, requestId);
    }
}
